package com.study.poolftp;

import cn.hutool.extra.ftp.Ftp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPool;

import java.nio.file.Paths;
import java.util.Objects;

/**
 * @author zhuzi
 * 2022/8/28 10:36
 */
@Slf4j
public class FtpProcessor {
    private GenericObjectPool<Ftp> pool;

    public GenericObjectPool<Ftp> getPool() {
        return pool;
    }

    public FtpProcessor(GenericObjectPool<Ftp> pool) {
        this.pool = pool;
    }

    public boolean downloadFile(String path, String localPath) {
        Ftp ftp = getFtp();
        try {
            ftp.download(path, Paths.get(localPath).toFile());
            return true;
        } catch (Exception e) {
            log.error("err", e);
            return false;
        } finally {
            releaseFtp(ftp);
        }
    }

    public Ftp getFtp() {
        try {
            return pool.borrowObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void releaseFtp(Ftp ftp) {
        if (Objects.nonNull(ftp)) {
            pool.returnObject(ftp);
        }
    }
}
